package com.definity.toolkit.ui.action;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.swing.SwingWorker;

public final class ProcessManager {

	private final String name;
	private final Map<String, ActionProcess<?>> processList = new HashMap<String, ActionProcess<?>>();
	
	ProcessManager(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public <T> void execute(final ActionProcess<T> actionProcess) {
		SwingWorker<T, Void> worker = new SwingWorker<T, Void>(){
			@Override
			protected T doInBackground() throws Exception {
				return actionProcess.run();
			}
			
			@Override
			protected void done() {
				actionProcess.done();
				removeProcess(actionProcess);
			}
		};
		addProcess(actionProcess, worker);
		actionProcess.execute();
	}
	
	public void kill(String processName) {
		ActionProcess<?> actionProcess = getProcess(processName);
		if (actionProcess == null)
			return;
		actionProcess.kill();
	}

	public void killAll() {
		for (ActionProcess<?> actionProcess : getProgressList())
			actionProcess.kill();
	}
	
	public Collection<ActionProcess<?>> getProgressList() {
		return processList.values();
	}

	@SuppressWarnings("unchecked")
	public <T> ActionProcess<T> getProcess(String processName) {
		return (ActionProcess<T>) processList.get(processName);
	}

	<T> void removeProcess(ActionProcess<T> actionProcess) {
		ActionProcess<?> process = processList.remove(actionProcess.getName());
		if (process != null) {
			process.destroy();
		}
	}

	private <T> void addProcess(ActionProcess<T> actionProcess, SwingWorker<T, Void> worker) {
		actionProcess.setWorker(this, worker);
		processList.put(actionProcess.getName(), actionProcess);
	}
	
}
